//
//  DiagramViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/1/4.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "DiagramViewController.h"
#import "DiagramCell.h"
#import "DiagramModel.h"
#import "UIImageView+WebCache.h"
#import "DiagramDetailViewController.h"

#define cellH H(160)

@interface DiagramViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong)UICollectionView *collectView;

@end

@implementation DiagramViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"图解问吧";
    [WShareUtil sharedData].j = 1;
    [self.view addSubview:self.collectView];
    [self requestListDataStrNum:@"1" isRefresh:YES];
    [self notifyRequestListData];
}

- (UICollectionView *)collectView {

    if (_collectView == nil) {

        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumLineSpacing= 10;
        flowLayout.minimumInteritemSpacing = 5;
        _collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT) collectionViewLayout:flowLayout];

        [_collectView registerNib:[UINib nibWithNibName:@"DiagramCell" bundle:nil] forCellWithReuseIdentifier:@"DiagramCell"];

        _collectView.backgroundColor = [UIColor whiteColor];
        _collectView.delegate = self;
        _collectView.dataSource = self;
    }
    return _collectView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

//    return 19;
    return [WShareUtil sharedData].arrMdiagram.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *NewCell = @"DiagramCell";
    DiagramCell *collectCell = [collectionView dequeueReusableCellWithReuseIdentifier:NewCell forIndexPath:indexPath];

    if ([WShareUtil sharedData].arrMdiagram[indexPath.row]) {
//        NSString *strNum = [NSString stringWithFormat:@"%@",[self.arrMdia[indexPath.row] ]];
        [collectCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[[WShareUtil sharedData].arrMdiagram[indexPath.row] imgsrc]] placeholderImage:[UIImage imageNamed:@"placeholderImage.png"]];
        collectCell.lbCell.text = [[WShareUtil sharedData].arrMdiagram[indexPath.row] strTitle];

        [UILabel changeSpaceForLabel:collectCell.lbCell];
//        collectCell.lbNumCell.text = strNum;
        //        collectCell.lbDateCell.text = [[self.arrMnew[indexPath.row] createtime] substringToIndex:10];
    }
    //    collectCell.backgroundColor = [UIColor redColor];
    return collectCell;
}

//设置元素的的大小框
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets top = {5,5,5,5};
    top = UIEdgeInsetsMake(8, 8, 8, 8);
    return top;
}

//设置顶部的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={0,0};
    return size;
}

//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    CGSize size = CGSizeZero;

    if (iPhone6_6s) {
        size = CGSizeMake((WSCREENH_WIDTH - 8 * 3) / 2.,cellH - 30);
    }else if (iPhone6Plus_6sPlus) {
        size = CGSizeMake((WSCREENH_WIDTH - 8 * 3) / 2.,cellH - 42);
    }else if (XIPHONE) {
        size = CGSizeMake((WSCREENH_WIDTH - 8 * 3) / 2.,cellH - 60);
    }else if (iPhone5SE){
        size = CGSizeMake((WSCREENH_WIDTH - 8 * 3) / 2.,cellH - 10);
    }else {
        size = CGSizeMake((WSCREENH_WIDTH - 8 * 3) / 2.,cellH);
    }
    return size;
}

//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    DiagramDetailViewController *diagramDetailVc = [[DiagramDetailViewController alloc] init];
    diagramDetailVc.title = @"图解问吧";
    diagramDetailVc.index = indexPath.row;
    
    if ([WShareUtil sharedData].arrMdiagram[indexPath.row]) {

        diagramDetailVc.strTitle = [[WShareUtil sharedData].arrMdiagram[indexPath.row] strTitle];//分享标题
        diagramDetailVc.strImage = [[WShareUtil sharedData].arrMdiagram[indexPath.row] imgsrc];//分享图片
        
        NSString *strContent = [[WShareUtil sharedData].arrMdiagram[indexPath.row] strContent];
        NSArray *array = [strContent componentsSeparatedByString:@"img src=\""];
        strContent = [array[1] componentsSeparatedByString:@"\""][0];
        diagramDetailVc.strUrl = strContent; //分享外链
    }
    
    [self.navigationController pushViewController:diagramDetailVc animated:YES];
//    [self requestCollectData:[self.arrMnew[indexPath.row] strId]];
}

- (void)notifyRequestListData{
    self.collectView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [WShareUtil sharedData].j = 1;
        [self requestListDataStrNum:@"1" isRefresh:YES];
    }];

    self.collectView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        NSString *num = [NSString stringWithFormat:@"%d",++[WShareUtil sharedData].j];
        [self requestListDataStrNum:num isRefresh:NO];
    }];
}

#pragma mark - 下载列表数据
- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{

    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"xxfb",@"content":@{@"revert":@"paginate",@"colcode":@"57",@"pagesize":@"10",@"pagenumber":pageNum}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        WLog(@"%@",returnDic[@"data"]);
        if (isRefresh) {
            [[WShareUtil sharedData].arrMdiagram removeAllObjects];
        }
        for (NSDictionary *dic in returnDic[@"data"]) {
            DiagramModel *diagramModel = [DiagramModel mj_objectWithKeyValues:dic];
            [[WShareUtil sharedData].arrMdiagram addObject:diagramModel];
        }

        [self.collectView reloadData];
        [self noWifiRefershingEnd];
        ///* --- 图片式提醒
        UIView *view = [self.collectView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if ([WShareUtil sharedData].arrMdiagram.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.collectView addSubview:_nonePage];
        }
        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.collectView.footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
        [self noWifiRefershingEnd];
    } showProgress:NO];
}

- (void)noWifiRefershingEnd {
    [self.collectView.header endRefreshing];
    [self.collectView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.collectView reloadData];
}

@end
